package org.opens.javaskill.thread.demo.producerConsumer;

public class ProducerConsumerVersion1 {

    private int i = 0;

    final private Object LOCK = new Object();

    private volatile boolean isProduced = false;

    public void produce() {
        synchronized (LOCK) {
            if ( isProduced ) {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                i++;
                System.out.println(Thread.currentThread().getName() + " >>> " + i);
                isProduced = true;
                LOCK.notify();
            }
        }
    }

    public void consume() {
        synchronized (LOCK) {
            if ( isProduced ) {
                System.out.println(Thread.currentThread().getName() + " <<< " + i);
                isProduced = false;
                LOCK.notify();
            } else {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        ProducerConsumerVersion1 producerConsumerVersion1 = new ProducerConsumerVersion1();

        new Thread("p1") {

            @Override
            public void run() {
                while (true) {
                    producerConsumerVersion1.produce();
                }
            }

        }.start();

        new Thread("p2") {

            @Override
            public void run() {
                while (true) {
                    producerConsumerVersion1.produce();
                }
            }

        }.start();

        new Thread("c1") {

            @Override
            public void run() {
                while (true) {
                    producerConsumerVersion1.consume();
                }
            }

        }.start();

        new Thread("c2") {

            @Override
            public void run() {
                while (true) {
                    producerConsumerVersion1.consume();
                }
            }

        }.start();
    }

}


